define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('jquery.ztree');
    require('doctor-select');

    $.module("SYS.sys_user", function () {
        var current_show_data = [];
        return {
            init: function () {
                this.loadData();
                this.loadEvent();
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;
                var search_nc_name = $("#search_cn_name").val();
                var search_username = $("#search_username").val();

                SYS.Core.ajax({
                    url: "sys/sysUserList",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        cn_name: search_nc_name,
                        name: search_username
                    },
                    success: function (data) {
                        var obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };
                        current_show_data = obj.data;
                        $("#myTable").bootstrapTable('destroy');    //销毁table
                        $('#myTable').bootstrapTable({
                            striped: true,      //使表格带有条纹
                            singleSelect: true,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination:'server',
                            clickToSelect: true,
                            idField: '_id',
                            data: obj.data,
                            columns: [
                                {field: 'checked', checkbox: true} ,
                                {field: 'cn_name', title: '昵称', align: 'center'},
                                {field: 'username', title: '用户名', align: 'center'},
                                {field: 'phone', title: '手机号', align: 'center'},
                                {field: 'company_id', title: '所属公司', align: 'center',
                                        formatter: function (val, row) {
                                            if (val) {
                                                let companyCode = row.company_code;
                                                let companyName = row.company_name;
                                                return companyCode + '-' + companyName + "<br/>(" + val +")";
                                            }
                                        }
                                },
                                // {field: 'platform_user', title: '平台用户', align: 'center',
                                //     formatter: function (val) {
                                //         if (!val) {
                                //             return '-';
                                //         }
                                //         return SYS.Tool.getUserImg(val.img) + "<br />" + decodeURI(val.nickname) + " (" + val._id + ")</a>";
                                //     }
                                // },
                                {field: 'create_time', title: '创建时间', align: 'center',
                                    formatter: function (time) {
                                        return SYS.Tool.formatterTime(time);
                                    }
                                },
                                {field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        var html = '';
                                        if(row.id > 0){
                                            html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toEdit('+index+')" class="text-do-edit"><i class="fa fa-pencil-square-o"></i> 编辑</a>';
                                            html += '<span class="text-explode"> | </span>';
                                            html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toEditUserRole('+row.id+',\''+row.username+'\')" class="text-do-edit"><i class="fa fa-user"></i> 分配角色</a>';
                                            html += '<span class="text-explode"> | </span>';
                                            html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toSelfMenu('+row.id+',\'' +row.username+ '\')" class="text-do-view"> 拥有权限</a>';
                                            html += '<span class="text-explode"> | </span>';
                                            html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toRemove('+row.id+')" class="text-do-remove"><i class="fa fa-trash-o"></i> 删除</a>';


                                            if(row.status == 0){
                                                html += '<span class="text-explode"> | </span>';
                                                html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toOnLine('+row.id+')" class="text-do-remove"><i class="fa fa-check"></i> 启用</a>';
                                            } else if(row.status == 1) {
                                                html += '<span class="text-explode"> | </span>';
                                                html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toOffLine('+row.id+')" class="text-do-remove"><i class="fa fa-close"></i> 禁用</a>';
                                            }

                                            html += '<span class="text-explode"> | </span>';
                                            html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toResetPwd('+row.id+')" class="text-do-remove"><i class="fa fa-refresh-o"></i> 重置密码</a>';
                                        }
                                        if(row._id == -1) {
                                            html += '<a href="javascript:void(0)" onclick="SYS.sys_user.toEdit(' + index + ')" class="text-do-edit"><i class="fa fa-pencil-square-o"></i> 编辑</a>';
                                        }
                                        return html;
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {   //表格右侧刷新按钮
                                that.loadData(obj.pageNumber, obj.pageSize);
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;
                $("#btn_search").on('click', function () {
                    that.loadData();
                });

                $("#btn_add").on('click', function () {
                    $("#fm input[name='_id']").val('');
                    $("#fm input[name='username']").val('');
                    $("#fm input[name='cn_name']").val('');
                    $("#fm input[name='phone']").val('');

                    $("#fm input[name='company_id']").val('').removeAttr('data-id').removeAttr('data-code').removeAttr('data-name');

                    $('#fm').bootstrapValidator('resetForm', true);

                    $('#myModal').modal('show');
                });

                $("#btn_save_user_role").on('click', function (){
                    that.saveUserRole();
                })

                // 报表项目父级
                $("#company_id").on('click', function () {
                    DOCTOR.Select.showCompany(this);
                });

                $('#fm').bootstrapValidator({
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        cn_name: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                }
                            }
                        },
                        username: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                }
                            }
                        },
                        phone: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^[1-9][0-9]*$/,
                                    message: '请输入正整数'
                                }
                            }
                        }
                    }
                }).on('success.form.bv', function (e) { //使用此方法可以ajax
                    e.preventDefault();
                    let CompanyId = $("#company_id").attr('data-id') || "";
                    if(CompanyId === "") {
                        $.messager.popup("请选择一个所属公司，在创建用户", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    //保存用户
                    that.saveUser();
                });

                //清空验证信息(必须)
                $('#myModal').on('hide.bs.modal', function() {
                    $("#fm input[name='_id']").val('');
                    $("#fm input[name='cn_name']").val('');
                    $("#fm input[name='username']").val('');
                    $("#fm input[name='phone']").val('');
                    $("#fm input[name='company_id']").val('')
                        .removeAttr('data-id')
                        .removeAttr('data-code')
                        .removeAttr('data-name');
                    $('#fm').bootstrapValidator('resetForm', true);
                });

                $("#platform_user").on('click', function () {
                    DOCTOR.Select.showUser(this);
                });
            },
            toEdit: function (index) {
                var obj = current_show_data[index];
                $("#fm input[name='_id']").val(obj.id);
                $("#fm input[name='cn_name']").val(obj.cn_name);
                $("#fm input[name='username']").val(obj.username);
                $("#fm input[name='phone']").val(obj.phone);
                $("#fm input[name='company_id']").val(obj.company_name)
                    .attr('data-id', obj.company_id)
                    .attr('data-code', obj.company_code)
                    .attr('data-name', obj.company_name);
                // if(obj.platform_user) {
                //     $("#platform_user").val(obj.platform_user.nickname + ' (ID:' + obj.platform_user._id + ')').attr('data-id', obj.platform_user._id);
                // }


                $('#myModal').modal('show');
            },
            toRemove: function (id) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "sys/delSysUser",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup('删除成功',"success");
                                that.loadData();
                            }else{
                                $.messager.popup('删除失败','error');
                            }
                        }
                    })
                });
            },
            toEditUserRole: function (id, username) {
                var that = this;
                $("#user_id").val(id);
                $("#user_name").val(username);
                SYS.Core.ajaxAsync({
                    url: "sys/sysRoleList",
                    common: {},
                    data: {},
                    success: function (data) {
                        if(data.code == 1){
                            var html = '';
                            //默认勾选功能,根据用户id获取角色ids
                            var roleIds = that.getSelRols();
                            html += '' +
                                '<thead> ' +
                                '<tr> ' +
                                '<th></th> ' +
                                '<th>角色名称</th> ' +
                                '<th>角色描述</th> ' +
                                '</tr>' +
                                '</thead>' +
                                '<tbody> ';
                            var rows = data.data.list;
                            for(var i=0; i<rows.length; i++){
                                html += '<tr>' +
                                    '<td><input type="checkbox" name="roleCheck" value="'+rows[i].id+'" ';
                                if($.inArray(rows[i].id, roleIds) != -1){
                                    html += 'checked="checked"';
                                }
                                html += '></td>' +
                                    '<td>' + rows[i].role_name + '</td>' +
                                    '<td>' + rows[i].role_desc + '</td>' +
                                    '</tr>';
                            }
                            html += '</tbody>';
                            $("#user_role_table").html(html);
                        } else{
                            $.messager.popup('操作失败', 'error');
                        }
                    }
                });
                $('#roleModal').modal('show');
            },
            saveUser: function (){
                var that = this;
                let id = $("#fm input[name='_id']").val();
                let cn_name = $("#fm input[name='cn_name']").val();
                let username = $("#fm input[name='username']").val();
                let phone = $("#phone").val();
                let company_id = $("#company_id").attr('data-id') || "";
                let company_code = $("#company_id").attr('data-code') || "";
                let company_name = $("#company_id").val() || "";

                var url = '';
                if(id==''){
                    url = 'sys/saveSysUser';
                }else{
                    url = 'sys/editSysUser';
                }
                SYS.Core.ajax({
                    url: url,
                    common: {},
                    data: {
                        id: id ? id : 0,
                        cn_name: cn_name,
                        username: username,
                        phone: phone,
                        company_id: company_id,
                        company_code: company_code,
                        company_name: company_name,
                    },
                    success: function (data) {
                        if(data.code == 1){
                            $('#myModal').modal('hide');

                            $.messager.popup(data.msg,'success');
                            that.loadData();

                            if (!id) {
                                $(".tip-pwd").html(data.msg)
                                $('#myPwdModal').modal('show');
                            }
                        }else{
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg,'error');
                        }
                    }
                })
            },
            saveUserRole: function () {
                var that = this;
                var userId = $("#user_id").val();
                var roleIds = new Array();
                $('input[name="roleCheck"]:checked').each(function () {
                    roleIds.push($(this).val());
                });

                SYS.Core.ajax({
                    url: "sys/editUserRole",
                    common: {},
                    data: {
                        id: userId,
                        roleIds: roleIds
                    },
                    success: function (data) {
                        if(data.code == 1){
                            $.messager.popup('保存成功', "success");
                            $('#roleModal').modal('hide');
                            that.loadData();
                        }else{
                            $.messager.alert('提示', '保存失败，请稍后再试', "error");
                        }
                    }
                })
            },
            getSelRols: function () {
                var arr = new Array();
                SYS.Core.ajaxAsync({
                    url: "sys/getRolesByUserId",
                    common: {},
                    data: {id: $("#user_id").val()},
                    success: function (data) {
                        if(data.code == 1){
                            var list = data.data;

                            for(var i=0; i<list.length; i++){
                                arr.push(list[i].role_id);
                            }
                        }
                    }
                });
                return arr;
            },
            toSelfMenu: function (id, username) {
                $.fn.zTree.destroy("tree");
                $("#menu_user_name").html(username);
                SYS.Core.ajax({
                    url: "user/getMenus",
                    common: {},
                    data: {
                        id: id
                    },
                    success: function (data) {
                        if(data.code == 1){
                            if(data.data.length == 0) {
                                $.messager.popup('用户没有可操作菜单', 'info');
                                return;
                            }
                            var setting = {
                                check: {
                                    enable: false
                                },
                                view: {
                                    showLine: true
                                },
                                data: {
                                    simpleData: {
                                        enable:true,
                                        idKey: "id",
                                        pIdKey: "pId",
                                        rootPId: ""
                                    }
                                },
                                callback: {
                                    beforeClick: function(treeId, treeNode) {
                                        var zTree = $.fn.zTree.getZTreeObj("tree");
                                        if (treeNode.isParent) {
                                            zTree.expandNode(treeNode);
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    }
                                }
                            };

                            var menus = data.data;
                            var zNodes = [];
                            if(menus.length > 0){
                                for(var i=0; i<menus.length; i++){
                                    var menu = menus[i];

                                    var zNode = {};
                                    zNode.id = menu.id;
                                    zNode.pId = menu.parent_id;
                                    zNode.name = menu.menu_name;
                                    zNode.open = false;
                                    zNodes.push(zNode);

                                    //二级菜单
                                    if(menu.children && menu.children.length > 0){
                                        for(var j=0; j<menu.children.length; j++){
                                            var childrenMenu = menu.children[j];

                                            var zNode = {};
                                            zNode.id = childrenMenu.id;
                                            zNode.pId = menu.id;
                                            zNode.name = childrenMenu.menu_name;
                                            zNode.open = false;
                                            zNodes.push(zNode);
                                            //三级菜单
                                            if(childrenMenu.children && childrenMenu.children.length > 0){
                                                for(var n=0; n<childrenMenu.children.length; n++){
                                                    var c = childrenMenu.children[n];
                                                    var z = {};
                                                    z.id = c.id;
                                                    z.pId = childrenMenu.id;
                                                    z.name = c.menu_name;
                                                    z.open = false;
                                                    z.checked = c.checked;
                                                    zNodes.push(z);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            $.fn.zTree.init($("#tree"), setting, zNodes);
                            $('#menuModal').modal('show');
                        } else{
                            $.messager.popup('操作失败', 'error');
                        }
                    }
                });
            },
            toOffLine: function (id) {
                var that = this;

                $.messager.confirm("确定要禁用吗？", function () {
                    SYS.Core.ajax({
                        url: "sys/sysUserOffline",
                        common: {},
                        data: {
                            id: id
                        },
                        success: function (data) {
                            if (data.code == 1) {
                                $.messager.popup('禁用成功', "success");

                                that.loadData();
                            } else {
                                $.messager.popup('禁用失败', 'error');
                            }
                        }
                    })
                });
            },
            toOnLine: function (id) {
                var that = this;
                $.messager.confirm("确定要启用吗？", function () {
                    SYS.Core.ajax({
                        url: "sys/sysUserOnline",
                        common: {},
                        data: {
                            id: id
                        },
                        success: function (data) {
                            if (data.code == 1) {
                                $.messager.popup('启用成功', "success");

                                that.loadData();
                            } else {
                                $.messager.popup('启用失败', 'error');
                            }
                        }
                    })
                });
            },
            toResetPwd: function (id) {
                var that = this;

                $.messager.confirm("确定要重置密码吗？", function() {
                    SYS.Core.ajax({
                        url: "user/resetPwd",
                        common: {},
                        data: {
                            id: id
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg,"success");
                                that.loadData();

                                $(".tip-pwd").html(data.msg)
                                $('#myPwdModal').modal('show');
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
        }
    });

    SYS.sys_user.init();
})